//
//  TYWebView.m
//  UnionMedApp
//
//  Created by 谢航宇_WORK on 2021/5/7.
//  Copyright © 2021 唐家钦. All rights reserved.
//

#import "TYWebView.h"
#import "Masonry.h"
#import <JavaScriptCore/JavaScriptCore.h>
@interface TYWebView () <UIWebViewDelegate,WKNavigationDelegate,WKUIDelegate,WKScriptMessageHandler>

@property (nonatomic,retain) NSMutableDictionary *handlerDic;
@end

@implementation TYWebView

- (instancetype)initWithUrl:(NSURL *)url {
    self = [super init];
    if (self) {
        self.url = url;
        self.userInteractionEnabled = YES;
        self.backgroundColor = [UIColor clearColor];
    }
    return self;
}

- (NSMutableDictionary *)handlerDic {
    if (!_handlerDic) {
        _handlerDic = [[NSMutableDictionary alloc]init];
    }
    return _handlerDic;
}

- (void)setUrl:(NSURL *)url {
    _url = url;
    [self loadUrlString:url.absoluteString type:(TYWebViewLoadTypeURL)];
}


- (void)loadUrlString:(NSString *)urlString type:(TYWebViewLoadType)type {
    _urlString = urlString;
    if (type == TYWebViewLoadTypeURL) {
        NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:urlString]];
        [self.webView loadRequest:request];
    }else if (type == TYWebViewLoadTypeLocalName) {
        NSURL *url = [NSURL fileURLWithPath:[[NSBundle mainBundle]bundlePath]];
        NSString *html = [NSString stringWithContentsOfFile:[[NSBundle mainBundle]pathForResource:urlString ofType:@"html"] encoding:NSUTF8StringEncoding error:nil];
        [self.webView loadHTMLString:html baseURL:url];
    }else if (type == TYWebViewLoadTypeHTMLString) {
        NSURL *url = [NSURL fileURLWithPath:[[NSBundle mainBundle]bundlePath]];
        [self.webView loadHTMLString:urlString baseURL:url];
    }
}

- (void)addWebViewObserve:(NSString *)name complete:(void(^)(id obj))complete {
    TYWebViewHandler * model = [[TYWebViewHandler alloc]initWithName:name complete:complete];
    [self.webView.configuration.userContentController addScriptMessageHandler:self name:name];
    [self.handlerDic setObject:model forKey:name];
}

- (void)dealloc{
    for (NSString * name in self.handlerDic.allKeys) {
        [self.webView.configuration.userContentController removeScriptMessageHandlerForName:name];
    }
    [self.webView removeObserver:self forKeyPath:@"estimatedProgress"];
    [self.webView removeObserver:self forKeyPath:@"title"];
}

- (WKWebView *)webView {
    if (!_webView) {
        WKWebViewConfiguration *configuration = [[WKWebViewConfiguration alloc] init];
        configuration.userContentController = [[WKUserContentController alloc]init];
        
        WKPreferences *preferences = [WKPreferences new];
        preferences.javaScriptCanOpenWindowsAutomatically = YES;
        preferences.minimumFontSize = 0;
        configuration.preferences = preferences;
        
        if (@available(iOS 11.0, *)) {
            NSArray *cookies = [[NSHTTPCookieStorage sharedHTTPCookieStorage] cookies];
            WKHTTPCookieStore *cookieStore = [WKWebsiteDataStore defaultDataStore].httpCookieStore;
            if (cookies.count > 0) {
                for (NSHTTPCookie *cookie in cookies) {
                    [cookieStore setCookie:cookie completionHandler:^{
                        
                    }];
                }
            }
        }
         
        _webView = [[WKWebView alloc] initWithFrame:self.frame configuration:configuration];
        _webView.backgroundColor = [UIColor clearColor];
        _webView.opaque = false;
        _webView.userInteractionEnabled = YES;
        _webView.navigationDelegate = self;
        _webView.UIDelegate = self;
        if(@available(iOS 11.0, *)) {
            _webView.scrollView.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;
        }
        
        [_webView addObserver:self forKeyPath:@"estimatedProgress" options:NSKeyValueObservingOptionNew context:NULL];
        [_webView addObserver:self forKeyPath:@"title" options:NSKeyValueObservingOptionNew context:NULL];
        [self addSubview:self.webView];
        __weak typeof(self) weakSelf = self;
        [_webView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.right.top.bottom.equalTo(weakSelf);
        }];
    }
    return _webView;
}



#pragma mark - WKNavigationDelegate
- (void)webView:(WKWebView *)webView decidePolicyForNavigationAction:(WKNavigationAction *)navigationAction decisionHandler:(void (^)(WKNavigationActionPolicy))decisionHandler {
    NSString * urlStr = navigationAction.request.URL.absoluteString;
    NSLog(@"%@",navigationAction.request.URL.scheme);
    if ([self.delegate respondsToSelector:@selector(webView:decidePolicyForNavigationAction:decisionHandler:)]) {
        [self.delegate webView:webView decidePolicyForNavigationAction:navigationAction decisionHandler:decisionHandler];
    }else if ([urlStr hasPrefix:@"image-preview-index"]){
        NSLog(@"打开图片：%@",urlStr);
        if ([self.delegate respondsToSelector:@selector(webView:didTouchImage:)]) {
            [self.delegate webView:webView didTouchImage:urlStr];
        }
        decisionHandler(WKNavigationActionPolicyCancel);
    }else {
        decisionHandler(WKNavigationActionPolicyAllow);
    }
}
- (void)webView:(WKWebView *)webView didStartProvisionalNavigation:(WKNavigation *)navigation {
    NSLog(@"准备加载页面");
    if ([self.delegate respondsToSelector:@selector(webView:didStartProvisionalNavigation:)]) {
        [self.delegate webView:webView didStartProvisionalNavigation:navigation];
    }
}

- (void)webView:(WKWebView *)webView didCommitNavigation:(WKNavigation *)navigation {
    NSLog(@"内容开始加载");
}

- (void)webView:(WKWebView *)webView didFinishNavigation:(WKNavigation *)navigation {
    NSLog(@"页面加载完成");
    if ([self.delegate respondsToSelector:@selector(webViewDidFinishLoad:)]) {
        [self.delegate webViewDidFinishLoad:webView];
    }
    //添加图片点击
    [self addImageScript];
}

- (void)webView:(WKWebView *)webView didFailNavigation:(WKNavigation *)navigation withError:(NSError *)error {
    NSLog(@"页面加载失败");
}

- (void)webView:(WKWebView *)webView didFailProvisionalNavigation:(WKNavigation *)navigation withError:(NSError *)error {
    NSLog(@"页面加载失败");
}

#pragma mark - WKScriptMessageHandler
- (void)userContentController:(WKUserContentController *)userContentController didReceiveScriptMessage:(WKScriptMessage *)message {
    TYWebViewHandler * model =  self.handlerDic[message.name];
    if (model) {
        model.complete(message.body);
    }
}

- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context {
    if ([keyPath isEqualToString:@"estimatedProgress"]) {
        if (object == _webView) {
            
        }
    }else if ([keyPath isEqualToString:@"title"]) {
        self.title = self.webView.title;
        if (object == self.webView) {
            if ([self.delegate respondsToSelector:@selector(webViewTitleDidChange:)]) {
                [self.delegate webViewTitleDidChange:self.webView];
            }
        }
    }
}

- (WKWebView *)webView:(WKWebView *)webView createWebViewWithConfiguration:(WKWebViewConfiguration *)configuration forNavigationAction:(WKNavigationAction *)navigationAction windowFeatures:(WKWindowFeatures *)windowFeatures {
    if (!navigationAction.targetFrame.isMainFrame) {
        [webView loadRequest:navigationAction.request];
    }
    return nil;
}
 
#pragma mark - 添加图片点击
- (void)addImageScript {
    
    //获取所以的图片标签
       [self.webView evaluateJavaScript:@"function getImages(){\
            var imgs = document.getElementsByTagName('img');\
            var imgScr = '';\
            for(var i=0;i<imgs.length;i++){\
                if (i == 0){ \
                   imgScr = imgs[i].src; \
                } else {\
                   imgScr = imgScr +'***'+ imgs[i].src;\
                } \
            };\
            return imgScr;\
        };" completionHandler:nil];//注入js方法

       __weak typeof(self)weakSelf = self;
       [self.webView evaluateJavaScript:@"getImages()" completionHandler:^(id _Nullable result, NSError * _Nullable error) {
//           if (!error) {
//
//               NSMutableArray * urlArray = result?[NSMutableArray arrayWithArray:[result componentsSeparatedByString:@"***"]]:nil;
//               NSLog(@"urlArray = %@",urlArray);
//               weakSelf.imageUrlArr = urlArray;
//           } else {
//               weakSelf.imageUrlArr = nil;
//           }
       }];
      
       //添加图片点击的回调
       [self.webView evaluateJavaScript:@"function registerImageClickAction(){\
           var imgs = document.getElementsByTagName('img');\
           for(var i=0;i<imgs.length;i++){\
               imgs[i].customIndex = i;\
               imgs[i].onclick=function(){\
                  window.location.href='image-preview-index:'+this.customIndex;\
               }\
           }\
       }" completionHandler:nil];
       [self.webView evaluateJavaScript:@"registerImageClickAction();" completionHandler:nil];
}
@end


@implementation TYWebViewHandler
- (instancetype)initWithName:(NSString *)name complete:(void(^)(id obj))complete {
    self = [super init];
    if (self) {
        self.name = name;
        self.complete = complete;
    }
    return self;
}
@end
